package com.wjk.kylin.mall.order.mq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Slf4j
@Component
public class RabbitCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * @param correlationData 发送消息时，要加上，才能有数据
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (!ack) {//确认
            log.error("cause:{},msgId:{}", cause, correlationData != null ? correlationData.getId() : "null");
        }
    }

    /**
     * 被交换机退回的消息 未找到queue
     * @param returnedMessage
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("--------------returnedMessage----------------");
        log.error("message = " + returnedMessage.getMessage());
        log.error("replyCode = " + returnedMessage.getReplyCode());
        log.error("replyText = " + returnedMessage.getReplyText());
        log.error("exchange = " + returnedMessage.getExchange());
        log.error("routingKey = " + returnedMessage.getRoutingKey());
        log.error("--------------returnedMessage----------------");
    }
}